<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 定时器 后台依然会运行；
        // requestAnimationFrame
        var num = 0;
        var timer;
        
        function autoplay() {
             timer = setInterval(function () {
                num++;
                document.title = num;
            }, 1000);
        }
        autoplay()
        console.log(timer);

        // 浏览器切换后台或者切换回来的时候会触发visibilitychange事件 ：
        // window.onvisibilitychange = function(){  // 不能触发；
        //     console.log("切换了");
        // }
        var flag = true;
        window.addEventListener("visibilitychange", function () {
            console.log(111);
            if (flag) {
                console.log("切换走了");
                clearInterval(timer);
            } else {
                console.log("切换回来了");
                autoplay();
            }
            flag = !flag;
        })


    </script>
</body>

</html>